# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :course.py
# @Time      :2022/7/26 11:08
# @Author    :吕华龙
from flask import Blueprint, jsonify, g
from flask_sqlalchemy import Pagination
from flask_restful import Api, Resource, reqparse, marshal

from models.model import *
from models.fields import *

cour_bp = Blueprint("cour_bp", __name__, url_prefix="/course")
api = Api(cour_bp)


# 课程视图
class CourseView(Resource):
    # 获取课程
    def get(self):
        print("------------->>>>>>>>>>>>>>>")
        req = reqparse.RequestParser()
        req.add_argument("id")
        args = req.parse_args()
        print("参数id", args['id'])
        try:
            print('-------------------------------')
            cour_info = Course.query.filter(Course.id == args['id']).first()
            print("查询课程成功", cour_info)
            data = {
                "id": cour_info.id,
                "name": cour_info.name,
                "info": cour_info.info,
                "create_time": cour_info.create_time,
                "start_time": cour_info.start_time,
                "end_time": cour_info.end_time,
                "total": cour_info.total,
                "total_time": cour_info.total_time,
                "photo": cour_info.photo,
                # "money":cour_info.money,
                "type": cour_info.type,
                "teacher_num": cour_info.teacher_num,
                "collect_num": cour_info.collect_num,
                "course_num": cour_info.course_num,
                "buy_num": cour_info.buy_num,
                "stu_num": cour_info.stu_num,
                "solo_num": cour_info.solo_num,
                "vip_free": cour_info.vip_free,
                # "excerpt":cour_info.excerpt
            }
            return jsonify({
                "code": 200,
                "msg": "查询课程大纲成功",
                "data": data
            })
        except Excerpt as e:
            print("查询课程大纲错误", e)
            return jsonify({
                "code": 400,
                "msg": "没有该课程"
            })

    # 删除课程
    def delete(self):
        resp = reqparse.RequestParser()
        resp.add_argument("id")
        args = resp.parse_args()

        # 获取该课程信息
        course_info = Course.query.filter(Course.id == args['id']).first()

        # 如果存在删除
        if course_info:
            Course.query.filter(Course.id == args['id']).delete()
            db.session.commit()
            return jsonify({'code': 200, 'msg': '删除课程成功', 'data': args['id']})
        else:
            return jsonify({'code': 400, 'msg': '该课程不存在'})

    # 更改上下架
    def put(self):
        resp = reqparse.RequestParser()
        resp.add_argument("id")
        resp.add_argument("status", type=int)
        args = resp.parse_args()

        # 获取课程信息
        course_info = Course.query.filter(Course.id == args['id']).first()

        # 如果存在就根据id修改状态
        if course_info:
            Course.query.filter(Course.id == args['id']).update({"status": bool(args['status'])})
            print(">>>>>>", type(args['status']))
            db.session.commit()
            # 如果状态等于1，返回上架成功
            course = Course.query.filter(Course.id == args['id']).first()
            print(course)
            print("-----------", course.status)
            print(course.status == 1)
            if course.status == 1:
                return jsonify({'code': 200, 'msg': '上架成功', 'data': course.id})
            # 否则返回下架成功
            else:
                return jsonify({'code': 200, 'msg': '下架成功', "data": course.id})

        # 否则就是课程不存在
        else:
            return jsonify({'code': 400, 'msg': '此课程不存在'})


# 课程
class CourseOneView(Resource):
    def put(self):
        resp = reqparse.RequestParser()
        resp.add_argument("id")
        resp.add_argument("is_top", type=int)
        args = resp.parse_args()

        # 获取课程信息
        course_info = Course.query.filter(Course.id == args['id']).first()

        # 如果此信息存在就更新是否置顶
        if course_info:
            Course.query.filter(Course.id == args['id']).update({"is_top": bool(args['is_top'])})
            db.session.commit()

            cou = Course.query.filter(Course.id == args['id']).first()
            # 获取出来信息，如果信息里的字段为True就是置顶
            if cou.is_top == 1:
                return jsonify({'code': 200, 'msg': '置顶成功', "data": cou.id})
            else:
                return jsonify({'code': 200, 'msg': '取消置顶成功', "data": cou.id})
        else:
            return jsonify({'code': 400, 'msg': '此信息不存在'})

    # 获取所有的课程
    def get(self):
        # 获取前端数据
        resp = reqparse.RequestParser()
        resp.add_argument("page", type=int)
        args = resp.parse_args()
        try:
            course: Pagination = Course.query.paginate(args['page'], 3, error_out=False)
        except Exception as e:
            print(e)
            return jsonify({'code': 400, "msg": '获取信息错误'})
        print("-----------------------------------", course.items)
        # 获取全部数据数量
        total = course.total
        # 获取当前页所有数据
        items = course.items
        # 获取当前页数
        page = course.page
        course_marshal = marshal(items, course_fields)
        # 构造数据格式
        list_1 = {
            "total": total,
            "page": page,
            "list": course_marshal
        }

        # 返回响应
        return jsonify({'code': 200, 'msg': '获取所有的课程成功', "data": list_1})


# 课程章节视图
class ExcerptView(Resource):
    def get(self):
        # 查询所有的课程章节数据
        excerpt = Excerpt.query.all()
        # course = excerpt.course
        print("00000-------", excerpt)
        # 构造数据格式
        for i in excerpt:
            course = i.course_id
            print(">>>>>>>>>>", course, type(course))
            # 根据章节获取对应的课程
            course_info = Course.query.filter(Course.id == course).first()
            # 根据课程获取对应的老师
            # cou = course2teacher.query.filter(course_info.id == )
            print(">>>>>>>>>>>>>>>>>>", course_info, course_info.name)
            list_1 = {
                "id": i.id,
                "name": i.name,
                "course": {
                    "id": course_info.id,
                    "name": course_info.name,
                    "info": course_info.info,
                    "create_time": course_info.create_time,
                    "start_time": course_info.start_time,
                    "end_time": course_info.end_time,
                    "total_time": course_info.total_time,
                    "total": course_info.total,
                    "status": course_info.status,
                    "is_top": course_info.is_top
                }
            }
            print("----------", list_1)
            return jsonify({'code': 200, 'msg': '获取章节成功', 'data': list_1})


from views.users import required_login


# 领取优惠券
class CouponView(Resource):
    # 领取优惠券
    @required_login
    def get(self):
        # 获取当前登录的用户id
        stu_id = g.stu["id"]
        print("-------------------", stu_id)
        # 获取前端数据
        resp = reqparse.RequestParser()
        resp.add_argument("coupon_id", type=int)
        args = resp.parse_args()
        # 先获取当前时间
        time_now = datetime.now()
        # 获取优惠券
        coupon = Coupon.query.filter(Coupon.id == args['coupon_id']).first()
        print("优惠券------------:", coupon.id)
        # coupon_marshal = marshal(coupon, coupon_fields)
        print("mmmmmmmmmmmmm", coupon)
        # print("mmmmmmmmmmmmm", coupon_marshal)
        # for i in coupon:
        # print("tttttttttttt", i)
        print("-=-=-=-=-=-=-==", time_now)
        # print("------------->>>>>>", i.create_time, i.end_time)
        # print("----------------================", stu_coupon.num)
        # 判断此优惠劵是否还在可领取时间内     并且此优惠劵没有被领取
        if coupon.create_time < time_now < coupon.end_time and coupon.coupon_num >= 1:
            # 如果此用户已领取过就不让在此领取
            # print(">>>>>>>>>>>>>>>>>>>>>>>>", stu_coupon.stu_id, type(stu_coupon.stu_id))
            # print(">>>>>>>>>>>>>>>>>>>>>>>>", stu_id, type(stu_id))
            # 获取此用户是否领取过优惠券
            stu_coupon = StuCoupon.query.filter(StuCoupon.stu_id == stu_id).first()
            if not stu_coupon:
                stu_coupon = StuCoupon(stu_id=stu_id, coupon_id=args['coupon_id'], num=1)
                db.session.add(stu_coupon)
                db.session.commit()
                return jsonify({'code': 200, 'msg': '领取优惠券成功'})
            return jsonify({'code': 400, 'msg': '此用户已经领取过了'})
        # 否则就是领取时间过期或者数量有被领取完返回响应
        else:
            return jsonify({'code': 400, 'msg': '此优惠券不能领取'})


# 创建路由
api.add_resource(CourseView, "/cour_info")
# 课程置顶
api.add_resource(CourseOneView, "/course_one")
# 课程的章节获取
api.add_resource(ExcerptView, "/excerpt")
# 领取优惠券
api.add_resource(CouponView, "/coupon")
